﻿/*
 * The MIT License (MIT)
 * 
 * Copyright (c) 2012 Brno University of Technology - Faculty of Information Technology (http://www.fit.vutbr.cz)
 * Author(s):
 * Vladimir Vesely (mailto:ivesely@fit.vutbr.cz)
 * Martin Mares
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace PcapMerger
{
    /// <remarks>
    /// Base class for all supproted file types
    /// </remarks>
    abstract class PmCaptureBase : IPmCapture
    {
        #region FileContentVariables

        protected List<IPmFrame> Frames; 
        protected PmSupportedTypes.CaptureFileTypes fileType;
        protected String FilePath;
        protected BinaryReader BinReader;

        #endregion

        #region Constructors

        /// <summary>
        /// Basic constructor - generaly for creating output file
        /// </summary>
        public PmCaptureBase(PmSupportedTypes.CaptureFileTypes fileType)
        {
            this.fileType = fileType;
            Frames = new List<IPmFrame>();
        }

        /// <summary>
        /// Load constructor - generaly for loading input from file
        /// (no need to call OpenFile after using this constructor)
        /// </summary>
        public PmCaptureBase(String filePath, BinaryReader fileReader, PmSupportedTypes.CaptureFileTypes fileType) :
            this(fileType)
        {
            OpenFile(filePath, fileReader);
        }

        #endregion

        #region IPmCaptureFileMethods

        #region OutputMethods

        public PmSupportedTypes.CaptureFileTypes FileType()
        {
            return fileType;
        }


        public String FileName()
        {
            return FilePath;
        }

        /// <summary>
        /// Close input file binary reader
        /// </summary>
        public List<IPmFrame> GetFrames()
        {
            return Frames;
        }

        /// <summary>
        /// Returns contained frames count
        /// </summary>
        public int Count()
        {
            return Frames.Count();
        }

        /// <summary>
        /// Timestamp of first included frame. MUST BE TESTED FOR NULL !
        /// </summary>
        //public DateTime? FirstTimeStamp()
        //{
        //    if (Frames.Any())
        //        return Frames.First().TimeStamp();

        //    return null;
        //}

        #endregion

        #region InputMethods

        public void AddFrames(List<IPmFrame> frames)
        {
            Frames.AddRange(frames);
        }

        public void SetFrames(List<IPmFrame> frames)
        {
            ClearFrameTable();
            if (frames != null)
            {
                Frames = frames;
            }
        }

        #endregion

        #region ControlMethods

        /// <summary>
        /// Open file and prepare for CreateFrameTable() method
        /// </summary>
        public void OpenFile(String filePath)
        {
            Close();
            BinReader = new BinaryReader(new FileStream(filePath, FileMode.Open));
        }

        /// <summary>
        /// Set input file and prepare for CreateFrameTable() method
        /// </summary>
        public void OpenFile(String filePath, BinaryReader binaryReader)
        {
            Close();
            if (binaryReader != null)
            {
                BinReader = binaryReader;
                FilePath = filePath;
            }
            else
            {
                OpenFile(filePath);
            }
        }

        /// <summary>
        /// Close input file binary reader
        /// </summary>
        public void Close()
        {
            if (BinReader != null)
                BinReader.Close();
            BinReader = null;
        }

        /// <summary>
        /// Drop current contained frames
        /// </summary>
        public void ClearFrameTable()
        {
            Frames.Clear();
        }

        #endregion

        #region NotImplementedMethods


        public abstract void CreateFrameTable();
        public abstract bool CreateOutput(String outputFile);
        public abstract DateTime? FirstTimeStamp();

        #endregion

        #region DebuggingMethods

        /// <summary>
        /// Function printing detail content of Frame Vector, purely for debugging purposes
        /// </summary>
        public void PrintFramesDetail()
        {
            Console.WriteLine("\n\nFRAMES INFORMATION FOR " + Path.GetFileName(FilePath));
            foreach (var fr in Frames)
            {
                PmConsolePrinter.PrintInfoEol("\nFrame {0}:", Frames.IndexOf(fr));
                PmConsolePrinter.PrintInfoEol("Offset> {0}", fr.FrameOffset());
                PmConsolePrinter.PrintInfoEol("Time Stamp> {0}", fr.TimeStamp().ToString("dd/MM/yyyy HH:mm:ss.FFFFFFF"));
                PmConsolePrinter.PrintInfoEol("Included Length> {0}", fr.IncludedLength());
                PmConsolePrinter.PrintInfoEol("Original Length> {0}", fr.OriginalLength());
            }
        }

        /// <summary>
        /// Function printing brief content of Frame Vector, purely for debugging purposes
        /// </summary>
        public void PrintFramesBrief()
        {
            PmConsolePrinter.PrintInfoEol("\n\nFRAMES INFORMATION FOR " + Path.GetFileName(FilePath));
            foreach (var fr in Frames)
                PmConsolePrinter.PrintInfoEol("Frame #{0}, {1}, {2}, {3}", Frames.IndexOf(fr), fr.FrameOffset(),
                                  fr.TimeStamp().ToString("dd/MM/yyyy HH:mm:ss.FFFFFFF"), fr.IncludedLength());
        }

        #endregion

        #endregion

    }
}
